using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
using QFramework;
using UnityEngine.U2D;
using UnityEngine.UI;

// 1.请在菜单 编辑器扩展/Namespace Settings 里设置命名空间
// 2.命名空间更改后，生成代码之后，需要把逻辑代码文件（非 Designer）的命名空间手动更改
namespace QFramework.Example
{
	public partial class UGUIInventoryExample : ViewController
	{ 
		// public class MyItemKitLoader : IItemKitLoader
		// {
		// 	// qframework的资源加载，每个要加载资源的脚本都必须要先写这个
		// 	// 下面这个是普通的resources资源加载
		// 	private ResLoader mResLoader = ResLoader.Allocate();
		// 	
		// 	// 下面的是加载AsssetBundle的资源，要先把资源标记为Mark
		// 	//public ResLoader ResLoader { get; set; }
		// 	public ItemDatabase LoadDatabase(string databaseName)
		// 	{
		// 		Debug.Log("开始加载database");
		// 		return mResLoader.LoadSync<ItemDatabase>("resources://"+databaseName);
		// 		//return ResLoader.LoadSync<ItemDatabase>(databaseName);
		// 	}
		//
		// 	public ItemLanguagePackage LoadLanguagePackage(string languagePackageName)
		// 	{
		// 		return mResLoader.LoadSync<ItemLanguagePackage>("resources://"+languagePackageName);
		// 		//return ResLoader.LoadSync<ItemLanguagePackage>(languagePackageName);
		// 	}
		//
		// 	public void LoadItemDatabaseAsync(string databaseName, Action<ItemDatabase> onLoadFinish)
		// 	{
		// 	}
		//
		// 	public void LoadItemLanguagePackageAsync(string languagePackageName, Action<ItemLanguagePackage> onLoadFinish)
		// 	{
		// 	}
		// }
		
		public class MyExcelItem:IItem
		{
			public string GetName { get; set; }
			public string GetKey { get; set; }
			public string GetDescription { get; set; }
			public ItemLanguagePackage.LocaleItem LocaleItem { get; set; }
			public Sprite GetIcon { get; set; }
			
			public bool IsWeapon { get; set; }
			public bool GetBoolean(string propertyName)
			{
				if (propertyName == "IsWeapon")
				{
					return IsWeapon;
				}

				return false;
			}

			public bool IsStackable { get; set; }
			public bool GetHasMaxStackableCount { get; set; }
			public int GetMaxStackableCount { get; set; }
		}
		
		private void Awake()
		{
			// 加载配置表
			var itemTextAsset = Resources.Load<TextAsset>("Items");
			var iconAtlas = Resources.Load<SpriteAtlas>("IconAtlas");
			var itemString=itemTextAsset.text;

			var itemRows = itemString.Split("\n");
			var line = 0;

			var excelItems = new List<MyExcelItem>();
			foreach (var itemRow in itemRows)
			{
				if (line==0)
				{
				}
				else
				{
					//Debug.Log("333");
					if (itemRow.IsTrimNotNullAndEmpty())
					{
						//Debug.Log("444");
						var itemFields=itemRow.Split(",");
						var key = itemFields[0];
						var name = itemFields[1];
						var description = itemFields[2];
						var iconName = itemFields[3];
						var stackableString = itemFields[4];
						var maxCountString = itemFields[5];
						var isWeaponString = itemFields[6];

						var item = new MyExcelItem()
						{
							GetKey = key,
							GetName = name,
							GetDescription = description,
							GetIcon = iconAtlas.GetSprite(iconName),
							IsStackable = int.Parse(stackableString) == 1,
							GetMaxStackableCount = int.Parse(stackableString),
							IsWeapon = int.Parse(isWeaponString) == 1,
						};
						excelItems.Add(item);
					}
				}
				line++;

			}
			Debug.Log(itemString);
			
			// 加载存档器
			ItemKit.SaverAndLoader = new MySaverAndLoader();
			// ItemKit.Loader = new MyItemKitLoader();
			
			// 加载配置数据
			ItemKit.LoadItemDatabase("ExampleItemDatabase");
			// 加载本地化数据，这里是英文，可能还会有其他语言
			ItemKit.LoadLanguagePackage("ItemEnglishPackage");
			
			// foreach (var item in excelItems)
			// {
			// 	ItemKit.ItemByKey.Add(item.GetKey,item);
			// 	Debug.Log(item.GetKey);
			// }

			//Debug.Log(ItemKit.ItemByKey.Count);
			excelItems.ForEach(item => ItemKit.ItemByKey.Add(item.GetKey, item));
			//Debug.Log(ItemKit.ItemByKey.Count);

			// 创建各个背包的数据，比如常规背包、武器栏、物品栏、宝箱等
			ItemKit.CreateSlotGroup("物品栏")
				.CreateSlot(Items.item_iron, 1)
				.CreateSlot(Items.item_greensword, 1)
				.CreateSlotByKey("iron_sword",3)
				.CreateSlotByKey("shoe",2)
				.CreateSlotsByCount(8);
			ItemKit.CreateSlotGroup("背包")
				.CreateSlotsByCount(15);
			ItemKit.CreateSlotGroup("武器")
				.CreateSlot(null, 0)
				.Condition(item => item.GetBoolean("IsWeapon"));
			ItemKit.CreateSlotGroup("宝箱")
				.CreateSlotsByCount(6);
			ItemKit.CreateSlotGroup("宝箱2")
				.CreateSlot(null, 0)
				.CreateSlot(null, 0)
				.CreateSlot(Items.item_greensword, 1)
				.CreateSlot(null, 0)
				.CreateSlot(null, 0)
				.CreateSlot(null, 0);
			
			// 加载物品数据库
			ItemKit.Load();

			var weaponSlot = ItemKit.GetSlotGroupByKey("武器").Slots[0];
			weaponSlot.Changed.Register(() =>
			{
				if (weaponSlot.Count!=0)
				{
					Debug.Log("成功切换武器："+weaponSlot.Item.GetName);
				}
			}).UnRegisterWhenGameObjectDestroyed(gameObject);
		}

		void Start()
		{
			// Code Here
			// 默认宝箱是隐藏的，需要手动显示
			TreasureBoxExample.Hide();
			
			BtnAddItem1.onClick.AddListener(() =>
			{
				var result=ItemKit.GetSlotGroupByKey("物品栏").AddItem(Items.item_iron,2);
				//Debug.Log("ReamainCount:"+result.RemainCount);
				if (!result.Succeed)
				{
						
					if (result.MessageTypes==SlotGroup.MessageTypes.Full)
					{
						Debug.Log("背包已满");
					}
				}
			});
			
			BtnAddItem2.onClick.AddListener(() =>
			{
				var result=ItemKit.GetSlotGroupByKey("物品栏").AddItem(Items.item_greensword);
				if (!result.Succeed)
				{
					if (result.MessageTypes==SlotGroup.MessageTypes.Full)
					{
						Debug.Log("背包已满");
					}
				}
			});
			
			BtnSubItem1.onClick.AddListener(() =>
			{
				ItemKit.GetSlotGroupByKey("物品栏").SubItem(Items.item_iron);
			});
			
			BtnSubItem2.onClick.AddListener(() =>
			{
				ItemKit.GetSlotGroupByKey("物品栏").SubItem(Items.item_greensword);
			});
			
			BtnAddItem3.onClick.AddListener(() =>
			{
				var result=ItemKit.GetSlotGroupByKey("物品栏").AddItem(Items.item_paper);
				if (!result.Succeed)
				{
					if (result.MessageTypes==SlotGroup.MessageTypes.Full)
					{
						Debug.Log("背包已满");
					}
				}
			});
			BtnAddItem4.onClick.AddListener(() =>
			{
				var result=ItemKit.GetSlotGroupByKey("物品栏").AddItem("iron_sword",3);
				if (!result.Succeed)
				{
					if (result.MessageTypes==SlotGroup.MessageTypes.Full)
					{
						Debug.Log("背包已满");
					}
				}
			});
			
			
			BtnSubItem3.onClick.AddListener(() =>
			{
				ItemKit.GetSlotGroupByKey("物品栏").SubItem(Items.item_paper);
			});

			BtnTreasureBox.onClick.AddListener(() =>
			{
				TreasureBoxExample.SetActive(!TreasureBoxExample.activeSelf);
				if (TreasureBoxExample.activeSelf)
				{
					var group = TreasureBoxExample.GetComponent<UISlotGroup>();
					group.RefreshWithGroupKey("宝箱");
				}
			});
			
			BtnTreasureBox2.onClick.AddListener(() =>
			{
				TreasureBoxExample.SetActive(!TreasureBoxExample.activeSelf);
				if (TreasureBoxExample.activeSelf)
				{
					var group = TreasureBoxExample.GetComponent<UISlotGroup>();
					group.RefreshWithGroupKey("宝箱2");
				}
			});
			
			BtnShop1.onClick.AddListener(() =>
			{
				var shopConfig = BtnShop1.GetComponent<ShopConfig>();
				UIShop.Title.text = shopConfig.ShopName;
				UIShop.Show(shopConfig.BuyItems);
			});
			
			BtnShop2.onClick.AddListener(() =>
			{
				UIShop.Title.text = "材料店";
				

				UIShop.SetSellPriceTable(new Dictionary<IItem,Func<int>>()
				{
					{Items.item_iron,()=>5}
				});
				
				UIShop.Show(new List<ShopConfig.ShopBuyItem>()
				{
					new ShopConfig.ShopBuyItem()
					{
						Item = Items.item_iron as Item,
						Price = 5,
						PriceGetter = () =>
							// 把物品栏中所有的Iron筛选出来，求数量之和，再加基础值5元则是最新的物品价格
							ItemKit.GetSlotGroupByKey("物品栏").GetItemCount(Items.item_iron)+5
					}
				});
			});

			void UpdateLanguageText()
			{
				if (ItemKit.CurrentLanguage==ItemKit.DefaultLanguage)
				{
					BtnLanguage.GetComponentInChildren<Text>().text = "简->EN";
				}
				else
				{
					BtnLanguage.GetComponentInChildren<Text>().text = "EN->简";
				}
			}
			
			UpdateLanguageText();
			BtnLanguage.onClick.AddListener(() =>
			{
				if (ItemKit.CurrentLanguage==ItemKit.DefaultLanguage)
				{
					ItemKit.LoadLanguagePackage("ItemEnglishPackage");
				}
				else
				{
					ItemKit.LoadLanguagePackage(ItemKit.DefaultLanguage);
				}
				UpdateLanguageText();
			});

		}

		private void OnApplicationQuit()
		{
			// 当游戏退出时，保存物品数据
			ItemKit.Save();
		}
	}
}
